using System;
using System.Security.Cryptography;
using System.Text;

namespace Framework.Library.Core.Utils.Security
{
    public class Crypto
    {
        private static readonly byte[] IV = new byte[] {240, 3, 0x2d, 0x1d, 0, 0x4c, 0xad, 0x3b};
        private static readonly TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();

        public static string Decrypt(string encryptedQueryString)
        {
            string str;
            try
            {
                byte[] inputBuffer = Convert.FromBase64String(encryptedQueryString);
                provider.Key = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes("ChangeThis!"));
                provider.IV = IV;
                str =
                    Encoding.UTF8.GetString(provider.CreateDecryptor().TransformFinalBlock(inputBuffer, 0,
                                                                                           inputBuffer.Length));
            }
            catch (CryptographicException cEx)
            {
                throw cEx;
            }
            catch (FormatException fEx)
            {
                throw fEx;
            }
            return str;
        }

        public static string Encrypt(string serializedQueryString)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(serializedQueryString);
            provider.Key = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes("ChangeThis!"));
            provider.IV = IV;
            return Convert.ToBase64String(provider.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length));
        }

        public static string MD5Encrypt(string plainText)
        {
            byte[] data, output;
            var encoder = new UTF8Encoding();
            var hasher = new MD5CryptoServiceProvider();

            data = encoder.GetBytes(plainText);
            output = hasher.ComputeHash(data);

            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }
    }
}